package com.wc.day15.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wc.day15.entity.Per;
import com.wc.day15.service.PerService;
import com.wc.day15.vo.PerVo;
import org.springboot.bw.struct.PageResult;
import org.springboot.bw.struct.Result;
import org.springboot.bw.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：王聪
 * @since 2022-07-05
 */
@RestController
@RequestMapping("/per")
public class PerController {
    @Resource
    PerService perService;

    @PostMapping("/search/{cp}/{pageSize}")
    public PageResult<Per> search(@PathVariable("cp")Integer cp,
                                  @PathVariable("pageSize")Integer pageSize,
                                  @RequestBody(required = false)PerVo vo) throws ParseException {
        QueryWrapper<Per> qw = new QueryWrapper<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(Objects.nonNull(vo)){
            if(StringUtils.isNotEmpty(vo.getPname())){
                qw.like("pname",vo.getPname());
            }
            if(StringUtils.isNotEmpty(vo.getBegindate()) && StringUtils.isNotEmpty(vo.getEnddate())){
                qw.between("times",simpleDateFormat.parse(vo.getBegindate()),simpleDateFormat.parse(vo.getEnddate()));
            }
        }

        Page<Per> objectPage = new Page<>(cp, pageSize);
        Page<Per> page = perService.page(objectPage, qw);
        PageResult<Per> of = PageResult.of(page.getRecords(), page.getTotal());
        return of;
    }


    @PostMapping("/add")
    public Result add(@RequestBody Per per){
        boolean save = perService.save(per);
        return save==true?Result.ok():Result.error();
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id")Integer id){
        boolean b = perService.removeById(id);
        return b==true?Result.ok():Result.error();
    }

    @PutMapping("/update")
    public Result update(@RequestBody Per per){
        Per byId = perService.getById(per.getId());

        byId.setPname(per.getPname());
        byId.setAge(per.getAge());
        byId.setTimes(per.getTimes());

        boolean b = perService.updateById(byId);
        return b==true?Result.ok():Result.error();
    }
}
